package com.eight.cloud.security.filter;

import cn.hutool.core.util.StrUtil;
import com.eight.cloud.redisson.utils.TokenManager;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;

import static com.eight.cloud.core.global.constant.StrConstant.AUTHORIZATION;


/**
 * 拦截器实现刷新Token
 *
 * @ClassName: JwtRequestFilter
 * @Author: TXC
 * @Date: 2025-07-08 10:54
 **/
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    @Resource
    private TokenManager tokenManager;
    private static final Long EXPIRE_TIME = 5 * 60 * 1000L;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = tokenManager.getAccessToken(request);
        if (StrUtil.isNotBlank(token) && tokenManager.isExpiration(token, EXPIRE_TIME)) {
            String refreshToken = tokenManager.refreshToken(token);
            // 设置token有效期
            long expireTimestamp = Instant.now().getEpochSecond() + tokenManager.getExpire();
            tokenManager.setLoginUserExpire(refreshToken, expireTimestamp);
            if (refreshToken != null) {
                response.setHeader(AUTHORIZATION, refreshToken);}
        }
        chain.doFilter(request, response);
    }
}
